package com.isnotlocus.gulimail.product.service.impl;

import com.isnotlocus.common.utils.constant.ProductConstant;
import com.isnotlocus.gulimail.product.dao.AttrAttrgroupRelationDao;
import com.isnotlocus.gulimail.product.dao.AttrGroupDao;
import com.isnotlocus.gulimail.product.dao.CategoryDao;
import com.isnotlocus.gulimail.product.entity.AttrAttrgroupRelationEntity;
import com.isnotlocus.gulimail.product.entity.AttrGroupEntity;
import com.isnotlocus.gulimail.product.entity.CategoryEntity;
import com.isnotlocus.gulimail.product.service.AttrAttrgroupRelationService;
import com.isnotlocus.gulimail.product.service.CategoryService;
import com.isnotlocus.gulimail.product.vo.AttrRelationVo;
import com.isnotlocus.gulimail.product.vo.AttrResponseVo;
import com.isnotlocus.gulimail.product.vo.AttrVO;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.isnotlocus.common.utils.PageUtils;
import com.isnotlocus.common.utils.Query;

import com.isnotlocus.gulimail.product.dao.AttrDao;
import com.isnotlocus.gulimail.product.entity.AttrEntity;
import com.isnotlocus.gulimail.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service()
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    AttrAttrgroupRelationDao relationDao;

    @Autowired
    CategoryService categoryService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional  //开启事务
    @Override
    public void saveAttr(AttrVO attr) {
        AttrEntity entity = new AttrEntity();
        //快速赋值attr的属性以及值到entity这里面去，前提是属性名一一对应
        BeanUtils.copyProperties(attr, entity);
        //先保存属性
        this.save(entity);
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelationEntity.setAttrId(entity.getAttrId());
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            //在属性和属性分组关联表中添加关联数据
            attrAttrgroupRelationService.save(attrAttrgroupRelationEntity);
        }

    }

    @Override
    public PageUtils SelectAttrByPage(Map<String, Object> map, Long categoryId, String attrType) {
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>();
        if (categoryId != 0) {
            wrapper.eq("catelog_id", categoryId);
        }
        String key = (String) map.get("key");
        if (StringUtils.isNotEmpty((String) map.get("key"))) {
            wrapper.and((obj) -> {
                obj.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        wrapper.and((obj) -> {
            obj.eq("attr_type", "base".equalsIgnoreCase(attrType) ? 1 : 0);

        });
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(map), wrapper);
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> list = page.getRecords();
        List<AttrResponseVo> resplist = list.stream().map((attrEntity) -> {
            AttrResponseVo attrResponseVo = new AttrResponseVo();
            BeanUtils.copyProperties(attrEntity, attrResponseVo);
            //设置分类和分组名字
            AttrAttrgroupRelationEntity attRelatior = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (attRelatior != null && attRelatior.getAttrGroupId() != null) {
                AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attRelatior.getAttrGroupId());
                attrResponseVo.setGroupname(attrGroupEntity.getAttrGroupName());
            }
            CategoryEntity categoryEntity = categoryDao.selectById(attrEntity.getCatelogId());
            if (categoryEntity != null) {
                attrResponseVo.setCategoryname(categoryEntity.getName());
            }
            return attrResponseVo;
        }).collect(Collectors.toList());
        pageUtils.setList(resplist);
        return pageUtils;
    }

    @Override
    public AttrResponseVo getAttrInfo(Long attrId) {
        AttrResponseVo respVo = new AttrResponseVo();
        AttrEntity attrEntity = this.getById(attrId);
        BeanUtils.copyProperties(attrEntity, respVo);
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = relationDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrId));
        if (attrAttrgroupRelationEntity != null) {
            respVo.setAttrGroupId(attrAttrgroupRelationEntity.getAttrGroupId());
            AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrAttrgroupRelationEntity.getAttrGroupId());
            if (attrGroupEntity != null) {
                respVo.setGroupname(attrGroupEntity.getAttrGroupName());
            }
        }
        Long catelogId = attrEntity.getCatelogId();
        Long[] catelogPath = categoryService.getParentCategoryPath(catelogId);
        respVo.setCatelogPath(catelogPath);

        CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
        if (categoryEntity != null) {
            respVo.setCategoryname(categoryEntity.getName());
        }
        return respVo;
    }

    @Transactional
    @Override
    public int UpdateByDetails(AttrVO attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.updateById(attrEntity);
        int i = 0;
        AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
        if (attr.getAttrGroupId() != null) {
            attrAttrgroupRelationEntity.setAttrGroupId(attr.getAttrGroupId());
            attrAttrgroupRelationEntity.setAttrId(attrEntity.getAttrId());
            Integer k = relationDao.selectCount(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            if (k > 0) {
                i = relationDao.update(attrAttrgroupRelationEntity, new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId()));
            } else {
                i = relationDao.insert(attrAttrgroupRelationEntity);
            }

        }
        return i;

    }

    @Override
    public List<AttrEntity> getAttrByAttrgourp(Long attrGroupId) {
        List<AttrAttrgroupRelationEntity> attr_group_ids = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_group_id", attrGroupId));
        List<AttrEntity> list1 = null;
        if (attr_group_ids.size() > 0) {
            List<Long> list = attr_group_ids.stream().map((obj) -> {
                return obj.getAttrId();
            }).collect(Collectors.toList());
            Collection<AttrEntity> attrEntities = this.listByIds(list);
            list1 = (List<AttrEntity>) attrEntities;
        }
        return list1;
    }

    @Transactional
    @Override
    public void deleteRelationByAttrIdAndGroupId(AttrRelationVo[] attrRelationVo) {
        //这种删除方式是频繁的发送数据库语句，所以不推荐
//        int delete = relationDao.delete(new UpdateWrapper<Attr
//                AttrgroupRelationEntity>().eq("attr_id", attrId).eq("attr_group_id", attrGroupId));
        int delete = 0;
        List<AttrAttrgroupRelationEntity> list = Arrays.asList(attrRelationVo).stream().map((item) -> {
            AttrAttrgroupRelationEntity attrAttrgroupRelationEntity = new AttrAttrgroupRelationEntity();
            BeanUtils.copyProperties(item, attrAttrgroupRelationEntity);
            return attrAttrgroupRelationEntity;
        }).collect(Collectors.toList());
        relationDao.deleteBatchRelation(list);
    }

    @Override
    public PageUtils getNotRelationAttr(Long AttrGroupId, Map<String, Object> map) {
        //当前分组只能关联当前分类下的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(AttrGroupId);
        QueryWrapper<AttrEntity> wrapper = null;
        List<Long> AttrGroupIds = null;
        if (attrGroupEntity != null) {
            Long categoryId = attrGroupEntity.getCatelogId();
            //当前分组只能关联到别的分组没有引用的属性
            //1)、查出其他分组的信息
            List<AttrGroupEntity> attrGroupList = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", categoryId));
            //2）、拿到其他分组的ID
            if (attrGroupList != null && attrGroupList.size() > 0) {
                AttrGroupIds = attrGroupList.stream().map((item) -> {
                    return item.getAttrGroupId();
                }).collect(Collectors.toList());
                List<AttrAttrgroupRelationEntity> list = relationDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", AttrGroupIds));
                if (list != null && list.size() > 0) {
                    List<Long> attrIds = list.stream().map((items) -> {
                        return items.getAttrId();
                    }).collect(Collectors.toList());
                    wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", categoryId).notIn("attr_id", attrIds);
                } else {
                    wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", categoryId);
                }
            }
        }
        PageUtils pageUtils = null;
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(map), wrapper);
        if (page != null) {
            pageUtils = new PageUtils(page);
        }
        return pageUtils;
    }

    @Override
    public List<Long> selectSearchAttrs(List<Long> attrIds) {
        return baseMapper.selectSearchAttrIds(attrIds);
    }
}